<?
  class Application_Model_Messages extends Zend_Db_Table_Abstract
  {
    protected $_name = "messages";
	protected $_rowClass = "Message";

	public function getUnreadCount($usersId)
	{
	   
		$res = $this->getAdapter()->query("SELECT COUNT(*) as count FROM messages");
		$count = $res->fetchAll();
		$msg_count = $count[0]['count'];

	  
		$res = $this->getAdapter()->query("SELECT COUNT(*) as count FROM messages_read where users_id = ".(int)$usersId);
		$count = $res->fetchAll();
		$read_count = $count[0]['count'];

		return $msg_count-$read_count;
	}
  }

  class Message extends Zend_Db_Table_Row
  {
    public function isRead($usersId)
	{
	  $msgReadTable = new Zend_Db_Table('messages_read');

	  $row = $msgReadTable->fetchRow($msgReadTable->select()->where('users_id = ?', $usersId)->where('messages_id = ?', $this->id));

	  if ($row)
	    return true;

	  return false;
	}

	public function setRead($usersId)
	{
	  $msgReadTable = new Zend_Db_Table('messages_read');

	  try
	  {
	    $msgReadTable->createRow( array ('users_id' => $usersId, 'messages_id' => $this->id) )
	  				 ->save();

		return true;
	  }
	  catch (Exception $e)
	  {
	    return false;
	  }
	}
  }


